//
//  KSCountDownButton.swift
//  KaisafinStockSwift
//
//  Created by 云 on 2020/1/2.
//  Copyright © 2020 administrator. All rights reserved.
//

import UIKit

class BYCountDownButton: UIButton {

    // 向外部提供可点击接口
    // 声明闭包,在外面使用时监听按钮的点击事件
    typealias ClickedClosure = (_ sender: UIButton) -> Void
    // 作为此类的属性
    var clickedBlock: ClickedClosure?
    /// 计时器
    private var countdownTimer: Timer?
    
    var isMainBtnType: Bool = false
    /// 计时器是否开启(定时器开启的时机)
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime(_:)), userInfo: nil, repeats:true)
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
            }
            setBtnEnable(!newValue)
        }
    }
    /// 剩余多少秒
    var remainingSeconds: Int = 5 {
        willSet {
            self.setTitle("\(self.resetTitle) (\(newValue)s)", for: .normal)
            setBtnEnable(newValue <= 0)
            if newValue <= 0 {
                self.setTitle(self.resetTitle, for: .normal)
                isCounting = false
            }
        }
    }
    
    var title: String = "获取验证码"{
        didSet{
            if self.title == oldValue { return }
            self.setTitle(self.title, for: .normal)
        }
    }
    
    var resetTitle: String = "重新获取"{
        didSet{
            if self.resetTitle == oldValue { return }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 初始化
        self.setupUI()
    }
    
    init(isMainBtnType:Bool = false) {
        super.init(frame: .zero)
        self.isMainBtnType = isMainBtnType
        // 初始化
        self.setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
        
    // 配置UI
    func setupUI() -> Void {
        self.setTitle(self.title, for:.normal)
        setBtnEnable(true)
        self.titleLabel?.font = PFSC_Regular(size: 14)
        self.addTarget(self, action: #selector(sendButtonClick(_:)), for: .touchUpInside)
    }
       
    // MARK: 点击获取验证码
    // 按钮点击事件(在外面也可以再次定义点击事件,对这个不影响,会并为一个执行)
    @objc func sendButtonClick(_ btn:UIButton) {
            
//            // 开启计时器
//            self.isCounting = true
//           // 设置重新获取秒数
//          self.remainingSeconds = 60
           
        // 调用闭包
        if clickedBlock != nil {
            self.clickedBlock!(btn)
        }
    }
       
    // 开启定时器走的方法
    @objc func updateTime(_ btn:UIButton) {
        remainingSeconds -= 1
    }
    
    //重置
    func reset() {
        if countdownTimer != nil {
            countdownTimer?.invalidate()
            countdownTimer = nil
        }
        self.setTitle(self.title, for:.normal)
        setBtnEnable(true)
    }
    
    func setBtnEnable(_ enable: Bool){
        if isMainBtnType {
            self.setTitleColor(kColor_white, for: .normal)
            enable ? (self.backgroundColor = kColor_main) : (self.backgroundColor = kColor_disableGray)
        }else{
            enable ? self.setTitleColor(kColor_main, for: .normal) : self.setTitleColor(kColor_detailTextGray, for: .normal)
            enable ? (self.borderColor = kColor_main) : (self.borderColor =  kColor_detailTextGray)
        }
        
        self.isEnabled = enable
    }
    
    deinit {
        if countdownTimer != nil {
            countdownTimer?.invalidate()
            countdownTimer = nil
        }
    }

}
